//
//  UserDetailViewController.m
//  IceBreaker
//
//  Created by Chiao Wolfire on 12-10-7.
//  Copyright (c) 2012年 NDS. All rights reserved.
//

#import "UserDetailViewController.h"
#import "TabsViewController.h"
#import "NSData+Base64.h"

@interface UserDetailViewController ()

@end

@implementation UserDetailViewController

@synthesize usernameLabel, genderLabel, phoneLabel, addressLabel, maleLabel, femaleLabel;
@synthesize usernameFeild, phoneFeild, addressFeild;
@synthesize cancelBtn, regBtn, maleBtn, femaleBtn, pickBtn;
@synthesize mySocket;
@synthesize headImg;
@synthesize testView;
@synthesize imagePicker;
@synthesize serverIP;
@synthesize connectPort;
@synthesize connectTime;

@synthesize user;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        // read configuration from bundle
        serverIP = [[NSUserDefaults standardUserDefaults] stringForKey: @"connectHost"];
        connectPort = [[NSUserDefaults standardUserDefaults] integerForKey: @"connectPort"];
        connectTime = [[NSUserDefaults standardUserDefaults] doubleForKey: @"connectTimeout"];
        NSLog(@"Configuration read: HOST:[%@], PORT:[%d], TIMEOUT:[%f]", serverIP, connectPort, connectTime);
    }
    return self;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"The mail box and password passed is [mailBox = %@, password = %@].", user.mailBox, user.passwd);
    user.gender = @"1"; // 1 for male, 0 for female
    usernameLabel.text = @"用户名";
    genderLabel.text = @"性别";
    phoneLabel.text = @"电话";
    addressLabel.text = @"住址";
    maleLabel.text = @"男";
    femaleLabel.text = @"女";
    usernameFeild.placeholder = @"用户名";
    [usernameFeild setDelegate: self];
    phoneFeild.placeholder = @"电话";
    [phoneFeild setDelegate: self];
    addressFeild.placeholder = @"地址";
    [addressFeild setDelegate: self];
    [cancelBtn setTitle: @"取消" 
               forState: UIControlContentHorizontalAlignmentCenter];
    [regBtn setTitle: @"注册" 
            forState: UIControlContentHorizontalAlignmentCenter];
    [pickBtn setTitle: @"设置头像"
             forState: UIControlContentHorizontalAlignmentCenter];
    [maleBtn setBackgroundImage: [UIImage imageNamed: @"checked_icon.png"] 
                       forState: UIControlStateNormal];
    [femaleBtn setBackgroundImage: [UIImage imageNamed: @"unchecked_icon.png"] 
                         forState: UIControlStateNormal];
    // init the image picker controller
    if (imagePicker == nil) {
        imagePicker = [[UIImagePickerController alloc] init];
    }
    
    NSLog(@"~~~~~%@~~~~~~%d~~~~~~%f~~~~~~", serverIP, connectPort, connectTime);    
    [self createConnection: serverIP
                      port: connectPort
                   timeout: connectTime];
}

-(void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    usernameLabel = nil;
    genderLabel = nil;
    phoneLabel = nil;
    addressLabel = nil;
    maleLabel = nil;
    femaleLabel = nil;
    usernameFeild = nil;
    phoneFeild = nil;
    addressFeild = nil;
    cancelBtn = nil;
    regBtn = nil;
    maleBtn = nil;
    femaleBtn = nil;
    pickBtn = nil;
    mySocket = nil;
    headImg = nil;
    testView = nil;
    imagePicker = nil;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction) regBtnTouched:(id)sender {
    if ([sender tag] == 0) {// cancel
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Tips" 
                                                        message: @"你确定要放弃注册？" 
                                                       delegate: self 
                                              cancelButtonTitle: @"放弃" 
                                              otherButtonTitles: @"继续", nil];
        [alert show];
        [alert release];
    } else {
        NSData *data1 = [@"M3" dataUsingEncoding: NSUTF8StringEncoding];
        NSString *str1 = [NSData encodeBase64: data1];
        NSData *data2 = [user.mailBox dataUsingEncoding: NSUTF8StringEncoding];
        NSString *str2 = [NSData encodeBase64: data2];
        NSData *data3 = [user.passwd dataUsingEncoding: NSUTF8StringEncoding];
        NSString *str3 = [NSData encodeBase64: data3];
        NSData *data4 = [usernameFeild.text dataUsingEncoding: NSUTF8StringEncoding];
        NSString *str4 = [NSData encodeBase64: data4];
        NSData *data5 = [user.gender dataUsingEncoding: NSUTF8StringEncoding];
        NSString *str5 = [NSData encodeBase64: data5];
        NSData *data6 = UIImageJPEGRepresentation(headImg, 1.0);
        NSString *str6 = [NSData encodeBase64: data6];
        
        NSString *sendStr = [str1 stringByAppendingString: @";"];
        sendStr = [sendStr stringByAppendingString: str2];
        sendStr = [sendStr stringByAppendingString: @";"];
        sendStr = [sendStr stringByAppendingString: str3];
        sendStr = [sendStr stringByAppendingString: @";"];
        sendStr = [sendStr stringByAppendingString: str4];
        sendStr = [sendStr stringByAppendingString: @";"];
        sendStr = [sendStr stringByAppendingString: str5];
        sendStr = [sendStr stringByAppendingString: @";"];
        sendStr = [sendStr stringByAppendingString: str6];
        sendStr = [sendStr stringByAppendingString: @";\r\n"];
        
        NSData *dataToSend = [sendStr dataUsingEncoding: NSUTF8StringEncoding];
        [mySocket writeData: dataToSend
                withTimeout: connectTime
                        tag: 0];
        
        
        TabsViewController *tabs = [[TabsViewController alloc] init];
        [self presentModalViewController: tabs animated:YES];
    }
}

-(IBAction) genderTouched:(id)sender {
    int tagIndex = [sender tag];
    user.gender = [NSString stringWithFormat: @"%d", tagIndex];
    if (tagIndex == 0) {// female        
        [maleBtn setBackgroundImage: [UIImage imageNamed: @"unchecked_icon.png"] 
                           forState: UIControlStateNormal];
        [femaleBtn setBackgroundImage: [UIImage imageNamed: @"checked_icon.png"] 
                             forState: UIControlStateNormal];
    } else {// male        
        [maleBtn setBackgroundImage: [UIImage imageNamed: @"checked_icon.png"] 
                           forState: UIControlStateNormal];
        [femaleBtn setBackgroundImage: [UIImage imageNamed: @"unchecked_icon.png"] 
                             forState: UIControlStateNormal];
    }
}


// touch the view to close the keyboard
-(IBAction)closeViewEdit:(id)sender {
    [usernameFeild resignFirstResponder];
    [phoneFeild resignFirstResponder];
    [addressFeild resignFirstResponder];
    self.view.center = CGPointMake(160, 250);
}

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            [self dismissModalViewControllerAnimated: YES];
            break;
        case 1:
            break;
        default:
            break;
    }
}

-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
    switch ([textField tag]) {
        case 0:
            break;
        case 1:
            break;
        case 2:
            self.view.center = CGPointMake(160, 220);
            break;
        default:
            break;
    }
    return YES;
}

#pragma mark - methods for UITextFieldDelegate
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [usernameFeild resignFirstResponder];
    [phoneFeild resignFirstResponder];
    [addressFeild resignFirstResponder];
    self.view.center = CGPointMake(160, 250);
    return YES;
}

-(BOOL) textViewShouldBeginEditing:(UITextView *)textView {
    self.view.center = CGPointMake(160, 80);
    NSLog(@"textView begin");
    return  YES;
}

#pragma mark - method for UIImagePickerControllerDelegate
-(void) imagePickerController: (UIImagePickerController *)picker
didFinishPickingMediaWithInfo: (NSDictionary *)info {
    NSMutableArray *images = [[[NSMutableArray alloc] init] autorelease];
    [images addObject: [info objectForKey: UIImagePickerControllerOriginalImage]];
    if ([images count] == 1) {
        headImg = (UIImage *)[images objectAtIndex: 0];
        testView.image = headImg;
        [self dismissModalViewControllerAnimated: YES];
    }
}

#pragma mark - instance methods
-(IBAction) pickImageFromAlbum {
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    
    [self presentModalViewController:imagePicker animated:YES];
}

-(IBAction) pickImageFromCamera {
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    
    [self presentModalViewController:imagePicker animated:YES];
}

-(int) createConnection: (NSString *)hostIP
                   port: (UInt16)hostPort
                timeout: (NSTimeInterval) timeout {
    if (self.mySocket == nil) {
        self.mySocket = [[AsyncSocket alloc] initWithDelegate: self];
        NSError *err = nil;
        
        if (![mySocket connectToHost: hostIP
                              onPort: hostPort
                         withTimeout: timeout
                               error: &err]) {
            NSLog(@"Something wrong with the connection, error code is [%d] and the error reads [%@]. Please check the network.", [err code], [err localizedDescription]);;
            return CONNECTION_FAIL;
        } else {
            NSLog(@"Connection OK");
            return CONNECTION_SUC;
        }
    } else {
        [mySocket readDataWithTimeout: -1
                                  tag: 0];
        return SRV_CONNECTED;
    }
}

-(IBAction)reConnect:(NSString *) hostIP
                port:(UInt16)hostPort
             timeout:(NSTimeInterval)timeout {
    NSLog(@"Trying to reconnect to the server, the host is [%@] while the port is [%d]", hostIP, hostPort);
    int stateCode = [self createConnection: hostIP
                                      port: hostPort
                                   timeout: timeout];
    switch (stateCode) {
		case SRV_CONNECTED:
			break;
		case CONNECTION_SUC:
			break;
        case CONNECTION_FAIL:
            break;
		default:
			break;
	}
}

#pragma mark - socket delegate
- (void)onSocket:(AsyncSocket *)sock
didConnectToHost:(NSString *)host
            port:(UInt16)port{
	[mySocket readDataWithTimeout: -1
                              tag: 0];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: [NSString stringWithFormat:@"Error %d", [err code]]
                                                    message: [NSString stringWithFormat:@"The connection failed, %@", [err localizedDescription]]
                                                   delegate: nil
                                          cancelButtonTitle: @"OK"
                                          otherButtonTitles: nil];
    [alert show];
    [alert release];
    NSLog(@"Error!!!!");
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
	NSLog(@"Sorry this connect is failure");
    [mySocket disconnect];
	mySocket = nil;
}

- (void)onSocketDidSecure:(AsyncSocket *)sock{
    
}

-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
    NSLog(@"thread(%@),onSocket:%p didWriteDataWithTag:%ld",[[NSThread currentThread] name], sock, tag);
}

- (void)onSocket: (AsyncSocket *)sock
     didReadData: (NSData *)data
         withTag: (long)tag{
    NSLog(@"Data read from server is [%@]", data);
	NSString* readStr = [[NSString alloc] initWithData: data
                                              encoding: NSUTF8StringEncoding];
	NSLog(@"Parse the data recieved a string [%@]",readStr);
	[mySocket readDataWithTimeout: -1
                              tag: 0];
    
    NSArray *responseData = [readStr componentsSeparatedByString: @";"];
    NSMutableArray *temArray = nil;
    for (NSString *str in responseData) {
        [temArray addObject: [[[NSString alloc] initWithData: [NSData decodeBase64: str]
                                                    encoding: NSUTF8StringEncoding] autorelease]];
    }
    NSArray *responseStrings = temArray;
    if (responseStrings) {
        for (NSString *str in responseStrings) {
            NSLog(@"~~~~%@~~~~", str);
        }
    }
}

@end
